import { defineStore } from "pinia";
import { reactive } from "vue";
import Cache from "@/common/utils/cache";
import useRequest from "@/common/hooks/useRequest";
import to from "await-to-js";
import Cookies from "js-cookie";
import { message } from "ant-design-vue";
export const useStore = defineStore('user', () => {
  const info = reactive({
    name: '甬教餐饮',
    isCustomer: false,
    token: null,
    yjToken: null,
    permissions: [],
  });
  const BASE_INFO = reactive({
    url: "",
    app: {
      url: "",
    }
  })

  const clearToken = () => {
    info.token = null;
  }

  const getInfo = async () => {
    try {
      const request = useRequest();
      //执行登录
      const loginAxios = new request.Axios(process.env.VUE_APP_LOGIN_API);
      let yjCookies = null as any;

      yjCookies = JSON.parse(Cookies.get('X6MC_LOGIN_INFO') as any);
      if (!yjCookies?.accessToken) {
        message.error('甬教登录状态异常');
        return;
      }
      loginAxios.setParams({
        grant_type: 'mobile', mobile: 'YONG@' + yjCookies?.userId, code: '', scope: 'server',
        realName: yjCookies?.realName, phone: yjCookies.phone, appid: '8b840350-9aec-46d2-b4c4-3bc99431c239', userId: yjCookies?.userId,
        clienttype: 'H5', yjToken: yjCookies?.accessToken,
      });
      loginAxios.setHeaders({
        'content-type': "application/x-www-form-urlencoded;charset=UTF-8",
        skipToken: false,
        'Enc-Flag': 'false',
        Authorization: 'Basic ' + btoa(process.env.VUE_APP_OAUTH2_PASSWORD_CLIENT),
      });
      let options: any = loginAxios.getOptions();
      //登录接口
      const [loginErr, loginRes]: any = await to(loginAxios.fetchSimple('getToken', options));
      if (loginErr) {
        message.error(loginErr.msg);
        return;
      }
      info.token = loginRes.data?.access_token || null;
      info.yjToken = yjCookies.accessToken;
      //获取用户信息接口(后端应用)
      const infoAxios = new request.Axios(process.env.VUE_APP_LOGIN_API);
      infoAxios.setHeaders({
        Authorization: 'Bearer ' + info.token,
      })
      infoAxios.setParams({
        applicationId: '497229972428029952'
      });
      let Ioptions: any = infoAxios.getOptions();
      const [Ierr, Ires]: any = await to(infoAxios.fetchSimple('getInfo', Ioptions));
      if (loginErr) {
        message.error(loginErr.msg);
        return;
      }
      info.permissions = Ires?.data?.data?.permissions || [];
      return true;
    } catch {
      return false;
    }
  }

  const initInfo = () => {
    info.isCustomer = false;
    info.token = null;
    info.yjToken = null;
    info.permissions = [];
  }

  const logout = () => {
    initInfo();
    Cookies.remove("X6MC_LOGIN_INFO", { domain: ".nbyongjiao.com" });
    BASE_INFO.url = window.location.href;
    BASE_INFO.app.url = window.location.href;
    const str = JSON.stringify(BASE_INFO)
    Cookies.set("X6MC_REDIRECT_INFO", str, { domain: ".nbyongjiao.com" });
    window.location.replace("https://login.nbyongjiao.com")
  }

  return {
    info,
    BASE_INFO,
    getInfo,
    clearToken,
    logout,
  }
}, {
  persist: {
    enabled: true,
    key: new Cache().defineKey('user'),
    pick: ['info.token', "BASE_INFO"],
    storage: localStorage,
  }
} as any)